package com.easylinkin.linkappapi.machinery.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.building.entity.Building;
import com.easylinkin.linkappapi.building.entity.Floor;
import com.easylinkin.linkappapi.building.mapper.BuildingMapper;
import com.easylinkin.linkappapi.building.mapper.FloorMapper;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.common.utils.NumberUtil;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.machinery.dto.ElevatorWorkStatisticsDTO;
import com.easylinkin.linkappapi.machinery.dto.MachineryIotDeviceDto;
import com.easylinkin.linkappapi.machinery.entity.ElevatorFloorRecord;
import com.easylinkin.linkappapi.machinery.entity.ElevatorWorkRecord;
import com.easylinkin.linkappapi.machinery.mapper.ElevatorFloorRecordMapper;
import com.easylinkin.linkappapi.machinery.mapper.ElevatorWorkRecordMapper;
import com.easylinkin.linkappapi.machinery.mapper.MachineryRecordMapper;
import com.easylinkin.linkappapi.machinery.service.ElevatorWorkRecordService;
import com.easylinkin.linkappapi.machinery.util.MachineryDeviceUtil;
import com.easylinkin.linkappapi.machinery.vo.ElevatorWorkStatisticsVO;
import com.easylinkin.linkappapi.machinery.vo.MachineryDeviceVo;
import com.easylinkin.linkappapi.openapi.dto.DatapushDTO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import com.easylinkin.linkappapi.shigongyun.service.MachineryMonitorBiService;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 升降机工作循环记录 服务实现类
 * </p>
 *
 * @author Xiaoyang
 * @since 2022-09-19
 */
@Slf4j
@Service
public class ElevatorWorkRecordServiceImpl extends
    ServiceImpl<ElevatorWorkRecordMapper, ElevatorWorkRecord> implements ElevatorWorkRecordService {

  @Autowired
  private DeviceService deviceService;

  @Autowired
  private MachineryRecordMapper machineryRecordMapper;

  @Resource
  private MachineryMonitorBiService machineryMonitorBiService;

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  @Override
  public Map<Integer, List<ElevatorWorkStatisticsVO>> getStatisticsOrderByMachinery(
      ElevatorWorkStatisticsVO statisticsVO) {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    List<Date> timeList = null;
    try {
      timeList = DateUtil.findDates(statisticsVO.getStartTime(), statisticsVO.getEndTime());
      if (CollectionUtil.isEmpty(timeList)) {
        return null;
      }
    } catch (ParseException e) {
      log.error("getStatisticsOrderByMachineryGlobal 群升降机 时间转换异常");
      throw new RuntimeException("getStatisticsOrderByMachineryGlobal 群升降机 时间转换异常" + e.getMessage());
    }
    String startTime = statisticsVO.getStartTime();
    String endTime = statisticsVO.getEndTime();
    Map<Integer, List<ElevatorWorkStatisticsVO>> map = new HashMap<>();
    if (CollectionUtil.isEmpty(statisticsVO.getMachineryIotList())) {
      // 过滤设备号
      MachineryDeviceVo machineryDeviceVo = new MachineryDeviceVo();
      machineryDeviceVo.setTypeCode("QUIP_SJJ_02");
      machineryDeviceVo.setTenantId(tenantId);
      List<MachineryIotDeviceDto> allMachineryIotDeviceDtos = machineryMonitorBiService
          .selectMachineryAndDeviceByCondition(machineryDeviceVo);
      if (CollectionUtil.isNotEmpty(allMachineryIotDeviceDtos)) {
        statisticsVO.setMachineryIotList(allMachineryIotDeviceDtos);
      }
    }
    if (CollectionUtil.isNotEmpty(statisticsVO.getMachineryIotList())) {
      for (MachineryIotDeviceDto dto : statisticsVO.getMachineryIotList()) {
        ElevatorWorkStatisticsVO req = new ElevatorWorkStatisticsVO();
        req.setMachineryId(dto.getId());
        req.setCode(dto.getDeviceCode());
        req.setStartTime(startTime);
        req.setEndTime(endTime);
        req.setTenantId(tenantId);
        List<ElevatorWorkStatisticsVO> dayList = getDayList(timeList, req);
        map.put(dto.getId(), dayList);
      }
    }
    return map;
  }

  @Override
  public Page getStatisticsDetailByMachinery(RequestModel<ElevatorWorkStatisticsVO> requestModel) {
    //构造返回值
    Page page = new Page();

    //获取天数
    String startTime = requestModel.getCustomQueryParams().getStartTime();
    String endTime = requestModel.getCustomQueryParams().getEndTime();
    List<Date> timeList = null;
    try {
      timeList = DateUtil.findDates(startTime, endTime);
      if (CollectionUtil.isEmpty(timeList)) {
        return null;
      }
    } catch (ParseException e) {
      log.error("getStatisticsOrderByMachineryGlobal 群升降机 时间转换异常");
      throw new RuntimeException("getStatisticsOrderByMachineryGlobal 群升降机 时间转换异常" + e.getMessage());
    }

    //根据分页信息进行获取新的开始结束时间
    page.setSize(requestModel.getPage().getSize());
    page.setTotal(timeList.size());
    page.setPages((long) Math.ceil(timeList.size() / (double) requestModel.getPage().getSize()));
    long current = requestModel.getPage().getCurrent();
    long size = requestModel.getPage().getSize();
    List<Date> collect = timeList;
    if (size!=-1){
      collect = timeList.stream().skip((current - 1) * size).limit(size).collect(Collectors.toList());
    }

    if (CollectionUtil.isNotEmpty(collect)){
      //参数处理
      String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
      String code = requestModel.getCustomQueryParams().getCode();
      ElevatorWorkStatisticsVO req = new ElevatorWorkStatisticsVO();
//    req.setMachineryId(machineryId);
      req.setCode(code);
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      req.setStartTime(simpleDateFormat.format(collect.get(0)));
      Date date = collect.get(collect.size() - 1);
      //获取这个时间点的最后时间
      DateTime dateTime = cn.hutool.core.date.DateUtil.endOfDay(date);
      String format = simpleDateFormat.format(dateTime);
      req.setEndTime(format);
      req.setTenantId(tenantId);
      List<ElevatorWorkStatisticsVO> dayList = getDayList(collect, req);

      //填充详细信息
      dayList.forEach(dayRecord->{
        String day = dayRecord.getDay();
        //获取这一天的开始结束时间
        String dayStartTime = day + " 00:00:00";
        String dayEndTime = day + " 23:59:59";
        req.setStartTime(dayStartTime);
        req.setEndTime(dayEndTime);
        List<ElevatorWorkStatisticsVO> hourList= getHourList(req);
        int sum = hourList.stream().mapToInt(ElevatorWorkStatisticsVO::getWorkCount).sum();
        dayRecord.setWorkCount(sum);
//        double totalPeriod = hourList.stream().mapToDouble(ElevatorWorkStatisticsVO::getPeriod).sum();
        hourList.stream().filter(item->item.getFirstStartTime()!=null).mapToLong(item->item.getFirstStartTime().getTime()).min().ifPresent(item->{
          dayRecord.setFirstStartTime(new Date(item));
        });
        hourList.stream().filter(item->item.getLastEndTime()!=null).mapToLong(item->item.getLastEndTime().getTime()).max().ifPresent(item->{
          dayRecord.setLastEndTime(new Date(item));
        });
        if(dayRecord.getFirstStartTime()!=null && dayRecord.getLastEndTime()!=null){
          dayRecord.setTotalPeriod(String.format("%.2f",Math.round(cn.hutool.core.date.DateUtil.between(dayRecord.getFirstStartTime(),dayRecord.getLastEndTime(), DateUnit.SECOND) /36.0)/100.0));
        }else {
          dayRecord.setTotalPeriod("0.00");
        }
        dayRecord.setHourList(hourList);
      });
      page.setRecords(dayList);
    }
    return page;
  }

  private List<ElevatorWorkStatisticsVO> getDayList(List<Date> timeList,
                                                    ElevatorWorkStatisticsVO statisticsVO) {
    // 初始化
    List<ElevatorWorkStatisticsVO> dayList = new ArrayList<>(timeList.size());
    FastDateFormat format = FastDateFormat.getInstance("yyyyMMdd");
    FastDateFormat format1 = FastDateFormat.getInstance("yyyy-MM-dd");
    // 查询统计
    List<ElevatorWorkStatisticsVO> result = baseMapper
        .getStatisticsOrderByMachineryGlobal(statisticsVO);

    // 初始化数据
    Map<String, ElevatorWorkStatisticsVO> resultMap = result.stream().collect(Collectors
        .toMap(ElevatorWorkStatisticsVO::getDay, Function
            .identity(), (k1, k2) -> k1));

    for (Date date : timeList) {
      String day = format.format(date);
      String refDate = format1.format(date);
      ElevatorWorkStatisticsVO vo = null;
      if (null != resultMap && resultMap.containsKey(day)) {
        vo = resultMap.get(day);
        vo.setRefDate(refDate);
        //计算总运行时长
//        if(vo.getLastEndTime()!=null && vo.getFirstStartTime()!=null){
//          vo.setTotalPeriod(String.format("%.2f", cn.hutool.core.date.DateUtil.between(vo.getFirstStartTime(),vo.getLastEndTime(), DateUnit.SECOND)/3600.0));
//        }
      } else {
        vo = new ElevatorWorkStatisticsVO();
        vo.setMachineryId(statisticsVO.getMachineryId());
        vo.setDay(day);
        vo.setWorkCount(0);
        vo.setWeight(0.0);
        vo.setTotalPeriod("0.00");
        vo.setRefDate(refDate);
      }
      dayList.add(vo);
    }
    if (CollectionUtil.isEmpty(dayList)) {
      return null;
    }
    for (ElevatorWorkStatisticsVO p : dayList) {
      Date day = DateUtil.parse(p.getDay(), "yyyyMMdd");
      String refDate = DateUtil.format(day, DateUtil.DATE_TIME_FORMAT_DAY);
      p.setDay(refDate);
    }
    return dayList;
  }

  private List<ElevatorWorkStatisticsVO> getHourList(ElevatorWorkStatisticsVO statisticsVO) {
    // 查询统计
    List<ElevatorWorkStatisticsVO> result = baseMapper.getStatisticsDetailByMachineryGlobal(statisticsVO);

    //填充没统计出来的数据
    List<String> times = result.stream().map(ElevatorWorkStatisticsVO::getHour).collect(Collectors.toList());
    for (int i=0;i<24;i++) {
        String time = i<10?"0"+i:i+"";
        if (!times.contains(time)) {
            ElevatorWorkStatisticsVO vo = new ElevatorWorkStatisticsVO();
            vo.setHour(time);
            vo.setWorkCount(0);
            vo.setWeight(0.0);
            vo.setPeriod(0.0);
            result.add(vo);
        }
    }
    result.sort(new Comparator<ElevatorWorkStatisticsVO>() {
      @Override
      public int compare(ElevatorWorkStatisticsVO o1, ElevatorWorkStatisticsVO o2) {
        return o1.getHour().compareTo(o2.getHour());
      }
    });
    return result;
  }

  @Override
  public List<ElevatorWorkStatisticsVO> getStatisticsOrderByMachineryTop(
      ElevatorWorkStatisticsVO statisticsVO) {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    statisticsVO.setTenantId(tenantId);
    List<ElevatorWorkStatisticsVO> statisticsOrderByMachineryTop = baseMapper
        .getStatisticsOrderByMachineryTopGlobal(statisticsVO);
    // 判空
    if (CollectionUtil.isEmpty(statisticsOrderByMachineryTop)) {
      return null;
    }
    //查询所有的升降机,进行数据填充
    List<MachineryIotDeviceDto> allMachineryIotDeviceDtos = getMachineryIotDeviceDtos(tenantId,"QUIP_SJJ_02");
    List<String> machineNames = statisticsOrderByMachineryTop.stream().map(item -> item.getMachineryName())
        .collect(Collectors.toList());
    // 判空
    if(CollectionUtil.isEmpty(allMachineryIotDeviceDtos)){
      return statisticsOrderByMachineryTop;
    }
    allMachineryIotDeviceDtos.stream().forEach(item->{
      if(!machineNames.contains(item.getName())){
        ElevatorWorkStatisticsVO vo = new ElevatorWorkStatisticsVO();
        vo.setMachineryName(item.getName());
        vo.setWorkCount(0);
        vo.setWeight(0d);
        statisticsOrderByMachineryTop.add(vo);
      }
    });
    return statisticsOrderByMachineryTop;
  }

  @Override
  public List<MachineryIotDeviceDto> getMachineryIotDeviceDtos(String tenantId, String typeCodes) {
    MachineryDeviceVo machineryDeviceVo = new MachineryDeviceVo();
//    machineryDeviceVo.setTypeCode("QUIP_SJJ_02"typeCodes);
    machineryDeviceVo.setTypeCode(typeCodes);
    machineryDeviceVo.setTenantId(tenantId);
    List<MachineryIotDeviceDto> allMachineryIotDeviceDtos = machineryMonitorBiService
        .selectMachineryAndDeviceByCondition(machineryDeviceVo);
    return allMachineryIotDeviceDtos;
  }

  @Override
  public ElevatorWorkStatisticsDTO getStatisticsSum(ElevatorWorkStatisticsVO statisticsVO) {
    ElevatorWorkStatisticsDTO result = new ElevatorWorkStatisticsDTO();
    result.setElevatorCount(0);
    result.setElevatorOnlineCount(0);
    result.setAvgWorkCount(0.0);
    result.setAvgWorkWeight(0.0);
    // 塔吊监测数
    Integer all = 0;
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    MachineryDeviceVo machineryDeviceVo = new MachineryDeviceVo();
    machineryDeviceVo.setTypeCode("QUIP_SJJ_02");
    machineryDeviceVo.setTenantId(tenantId);
    List<MachineryIotDeviceDto> allMachineryIotDeviceDtos = machineryMonitorBiService
        .selectMachineryAndDeviceByCondition(machineryDeviceVo);
    if (CollectionUtil.isNotEmpty(allMachineryIotDeviceDtos)) {
      all = allMachineryIotDeviceDtos.size();
      result.setElevatorCount(all);
    } else {
      return null;
    }
    // 在线数
    Integer online = 0;
    machineryDeviceVo.setOnlineState(1);
    List<MachineryIotDeviceDto> onlineMachineryIotDeviceDtos = machineryMonitorBiService
        .selectMachineryAndDeviceByCondition(machineryDeviceVo);
    if (CollectionUtil.isNotEmpty(onlineMachineryIotDeviceDtos)) {
      online = onlineMachineryIotDeviceDtos.size();
      result.setElevatorOnlineCount(online);
    }
    // 查询塔吊总数据
    List<String> codeList = allMachineryIotDeviceDtos.stream()
        .map(MachineryIotDeviceDto::getDeviceCode)
        .collect(Collectors.toList());
    statisticsVO.setCodeList(codeList);
    statisticsVO.setTenantId(tenantId);
    ElevatorWorkStatisticsVO statisticsSum = baseMapper.getStatisticsSum(statisticsVO);
    if (null != statisticsSum) {
      if (null != statisticsSum.getWorkCount()) {
        Double avgWorkCount = NumberUtil
            .div(statisticsSum.getWorkCount().doubleValue(), all.doubleValue(), 2);
        result.setAvgWorkCount(avgWorkCount);
      }
      if (null != statisticsSum.getWeight()) {
        Double avgWorkWeight = NumberUtil
            .div(statisticsSum.getWeight().doubleValue(), all.doubleValue(), 2);
        result.setAvgWorkWeight(avgWorkWeight);
      }
    }
    return result;
  }

  @Resource
  private FloorMapper floorMapper;

  @Resource
  private BuildingMapper buildingMapper;

  @Resource
  private ElevatorFloorRecordMapper elevatorFloorRecordMapper;

  private Floor getFloor(Double installOffset, Integer buildingId, Double height) {
    // 判断是暂留第几层
    Floor floor = null;
    // 安装偏差值
    QueryWrapper<Floor> modelQueryWrapper = new QueryWrapper<>();
    //设置查询条件
    modelQueryWrapper.eq("building_id", buildingId)
        .eq("type", 2);
    List<Floor> floors = floorMapper.selectList(modelQueryWrapper);
    if (CollectionUtil.isNotEmpty(floors)) {
      for (Floor f : floors) {
        if (null == f.getBuildingStandardHeight()) {
          continue;
        }
        Double floorHeight = floatToDouble(f.getStructureStandardHeight());
        if (floorHeight < 0) { //
          continue;
        }
        Double floorHeightMax =
            installOffset == null ? floorHeight : NumberUtil.add(floorHeight, installOffset, 2);
        Double floorHeightMin =
            installOffset == null ? floorHeight : NumberUtil.sub(floorHeight, installOffset, 2);
        if (height.compareTo(floorHeightMin) >= 0 && height.compareTo(floorHeightMax) <= 0) {
          floor = f;
        }
      }
    }
    return floor;
  }

  @Override
  public List<MachineryIotDeviceDto> getElevatorDevice() {
    String tenantId = linkappUserContextProducer.getCurrent().getTenantId();
    return getMachineryIotDeviceDtos(tenantId,"QUIP_SJJ_02");
  }

  @Override
  public void datapushHandler(DatapushDTO datapushDTO) {
    // 流水处理流程
    if (null != datapushDTO && null != datapushDTO.getData()) {
      JSONObject data = datapushDTO.getData();
      String deviceCode = datapushDTO.getDevice_id();
      // 1.校验流水
      // 1.1 校验是否属于塔机流水
//      Device device = new Device();
//      device.setCode(deviceCode);
//      List<Device> deviceList = deviceService.selectDevices(device);
//      if (deviceList == null || deviceList.size() <= 0) {
//        return;
//      }
//      device = deviceList.get(0);

      // 将查询逻辑放入主线程
      Device device = datapushDTO.getDevice_data_latest();

      String deviceUnitCodeConfigKey = "MACHINERY_TYPE_QUIP_SJJ_02";
      if (!MachineryDeviceUtil.isBelongSpecifiedDeviceType(device, deviceUnitCodeConfigKey)) {
        return;
      }
      // 1.2 校验流水是否关联电子档案
      MachineryDeviceVo machineryDeviceVo = new MachineryDeviceVo();
      machineryDeviceVo.setBinded(1);
      machineryDeviceVo.setTenantId(device.getTenantId());
      machineryDeviceVo.setDevice(device);
      // 查询关联的电子档案
      List<MachineryIotDeviceDto> ls = machineryRecordMapper
          .queryMachineryAndDeviceList(machineryDeviceVo);
      if (CollectionUtil.isEmpty(ls)) {
        return;
      }
      MachineryIotDeviceDto machineryIotDeviceDto = ls.get(0);
      // 1.3 流水消息类型
      Integer msgType = data.getInteger("msg_type");
      if (null == msgType) {
        return;
      }
      // 2.处理循环数据类型数据
      // 2.1 获取工作循环数据
      if (2 == msgType) {
        try {
          /**
           * start_time
           * end_time
           * driver_name
           * max_weight
           * weight_percentage
           * start_height
           * end_height
           * stroke_height
           * rise_direction
           * average_speed
           * max_tilt_x
           * max_tilt_y
           */
          Date start_time = data.getDate("start_time");
          Date end_time = data.getDate("end_time");
          String driver_name = data.getString("driver_name");
          Double max_weight = data.getDouble("max_weight");
          Double weight_percentage = data.getDouble("weight_percentage");
          Double start_height = data.getDouble("start_height");
          Double end_height = data.getDouble("end_height");
          Double stroke_height = data.getDouble("stroke_height");
          Integer rise_direction = data.getInteger("rise_direction");
          Double average_speed = data.getDouble("average_speed");
          Double max_tilt_x = data.getDouble("max_tilt_x");
          Double max_tilt_y = data.getDouble("max_tilt_y");

          // 2.2 塔机工作循环数据构造
          ElevatorWorkRecord elevatorWorkRecord = new ElevatorWorkRecord();
          elevatorWorkRecord.setMachineryId(machineryIotDeviceDto.getId());
          elevatorWorkRecord.setDeviceCode(device.getCode());
          elevatorWorkRecord.setTenantId(device.getTenantId());
          elevatorWorkRecord.setCreateTime(new Date());
          elevatorWorkRecord.setStartTime(start_time);
          elevatorWorkRecord.setEndTime(end_time);
          elevatorWorkRecord.setDriverName(driver_name);
          elevatorWorkRecord.setMaxWeight(max_weight);
          elevatorWorkRecord.setWeightPercentage(weight_percentage);
          elevatorWorkRecord.setStartHeight(start_height);
          elevatorWorkRecord.setEndHeight(end_height);
          elevatorWorkRecord.setStrokeHeight(stroke_height);
          elevatorWorkRecord.setRiseDirection(rise_direction);
          elevatorWorkRecord.setAverageSpeed(average_speed);
          elevatorWorkRecord.setMaxTiltX(max_tilt_x);
          elevatorWorkRecord.setMaxTiltY(max_tilt_y);
          // 2.3入库
          baseMapper.insert(elevatorWorkRecord);
        } catch (Exception e) {
          log.error("ElevatorWorkRecord datapushHandler error:{}", e.getMessage());
        }

      } else if (4 == msgType) {
        Integer buildingId = machineryIotDeviceDto.getBuildingId();
        Building building = buildingMapper.getOneById(buildingId);
        if (null != building) {
          // 3 实时数据
          /**
           * weight
           * height
           * speed
           * direction
           * front_door
           * after_door
           * tilt_x
           * tilt_y
           */
          ElevatorFloorRecord elevatorFloorRecord = null;
          Double installOffset = machineryIotDeviceDto.getInstallOffset();
          // 1.判断开关门
          Double height = data.getDouble("height");
          Integer front_door = data.getInteger("front_door");
          Integer after_door = data.getInteger("after_door");
          Integer doorStatus = null;
          if (front_door.equals(after_door) && front_door == 0) {
            doorStatus = 0;
          }
          if (front_door == 1 || after_door == 1) {
            doorStatus = 1;
          }
          if (doorStatus == null) {
            return;
          }
          // 2.判断库里是否有上一次关门信息
          QueryWrapper<ElevatorFloorRecord> modelQueryWrapper = new QueryWrapper<>();
          //设置查询条件
          modelQueryWrapper.eq("machinery_id", machineryIotDeviceDto.getId())
              .eq("device_code", deviceCode)
              .eq("tenant_id_", device.getTenantId())
              .eq("door_status", 0)
              .orderByDesc("create_time_");
          List<ElevatorFloorRecord> elevatorFloorRecords = elevatorFloorRecordMapper
              .selectList(modelQueryWrapper);
          if(CollectionUtil.isNotEmpty(elevatorFloorRecords)){
            elevatorFloorRecord = elevatorFloorRecords.get(0);
          }
          if (null == elevatorFloorRecord) {
            if (0 == doorStatus) { // 状态为关门
              // 保存关门信息
              elevatorFloorRecord = new ElevatorFloorRecord();
              elevatorFloorRecord.setMachineryId(machineryIotDeviceDto.getId());
              elevatorFloorRecord.setDeviceCode(device.getCode());
              elevatorFloorRecord.setTenantId(device.getTenantId());
              elevatorFloorRecord.setCreateTime(new Date());
              elevatorFloorRecord.setCloseTime(new Date());// 关门时间
              elevatorFloorRecord.setHeight(height);// 关门高度
              elevatorFloorRecord.setDoorStatus(doorStatus);
              elevatorFloorRecordMapper.insert(elevatorFloorRecord);
            }
          } else {
            Double colseHeigth = elevatorFloorRecord.getHeight();
            if (1 == doorStatus && !colseHeigth.equals(height)) { // 状态开门 并且高度变化
              Floor floor = getFloor(installOffset, buildingId, height);
              if (null != floor) {
                elevatorFloorRecord.setFloorId(floor.getId());
                elevatorFloorRecord.setFloorName(floor.getName());
                elevatorFloorRecord.setBuildingId(building.getId());
                elevatorFloorRecord.setBuildingName(building.getName());
                elevatorFloorRecord.setOpenTime(new Date());
                elevatorFloorRecord.setModifyTime(new Date());
                elevatorFloorRecord.setHeight(height);//开门高度
                elevatorFloorRecord.setDoorStatus(doorStatus);
                elevatorFloorRecordMapper.updateById(elevatorFloorRecord);
              }

            }
          }


        }

      }


    }
  }

  public static void main(String[] args) {
    Double floorHeightMax = 6.1;
    Double floorHeightMin = 5.9;
    Double height = 6.0;
    System.out.println(height.compareTo(floorHeightMin));
    System.out.println(height.compareTo(floorHeightMax));
    System.out.println(height.compareTo(floorHeightMin) >= 0);
    System.out.println(height.compareTo(floorHeightMax) <= 0);
  }

  private Double floatToDouble(Float f){
    BigDecimal b = new BigDecimal(String.valueOf(f));
    Double d = b.doubleValue();
    return d;
  }
}
